<?php
use think\Db;
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

// 应用公共文件
/* 
 * 加密--32位密码
 */
function md5_salt($password) {
	return md5(crypt($password, config('salt')));
}


		/**
	 * 调用成功
	 */
function toSuccess($msg='', $data='') {
		return json(['code'=>200,'msg'=>$msg,'data'=>$data]);
	}
	/**
	 * 调用失败
	 */
function toError($code='', $msg='', $data='') {
		return json(['code'=>$code,'msg'=>$msg,'data'=>$data]);
	}
	

/**
 * 返回格式化后的当前时间
 */
function now_time(){
	return date('Y-m-d H:i:s',time());
}


/**
 * 构建层级（树状）数组
 * @param array  $array 要进行处理的一维数组，经过该函数处理后，该数组自动转为树状数组
 * @param string $pid 父级ID的字段名
 * @param string $child_key_name 子元素键名
 * @return array|bool
 */
function array2tree(&$array, $pid = 'pid', $child_key_name = 'children') {
    $counter = array_children_count($array, $pid);
    if ($counter[0] == 0)
        return false;
    $tree = [];
    while (isset($counter[0]) && $counter[0] > 0) {
        $temp = array_shift($array);
        if (isset($counter[$temp['id']]) && $counter[$temp['id']] > 0) {
            array_push($array, $temp);
        } else {
            if ($temp[$pid] == 0) {
                $tree[] = $temp;
            } else {
                $array = array_child_append($array, $temp[$pid], $temp, $child_key_name);
            }
        }
        $counter = array_children_count($array, $pid);
    }

    return $tree;
}


/**
 * 子元素计数器
 * @param $array
 * @param $pid
 * @return array
 */
function array_children_count($array, $pid) {
    $counter = [];
    foreach ($array as $item) {
        $count = isset($counter[$item[$pid]]) ? $counter[$item[$pid]] : 0;
        $count++;
        $counter[$item[$pid]] = $count;
    }

    return $counter;
}


/**
 * 把元素插入到对应的父元素$child_key_name字段
 * @param        $parent
 * @param        $pid
 * @param        $child
 * @param string $child_key_name 子元素键名
 * @return mixed
 */
function array_child_append($parent, $pid, $child, $child_key_name) {
    foreach ($parent as &$item) {
        if ($item['id'] == $pid) {
            if (!isset($item[$child_key_name]))
                $item[$child_key_name] = [];
            $item[$child_key_name][] = $child;
        }
    }

    return $parent;
}


/**
 * 数组层级缩进转换
 * @param array $array
 * @param int   $pid
 * @param int   $level
 * @return array
 */
function array2level($array, $pid = 0, $level = 1) {
    static $list = [];
    foreach ($array as $v) {
        if ($v['pid'] == $pid) {
            $v['level'] = $level;
            $list[]     = $v;
            array2level($array, $v['id'], $level + 1);
        }
    }

    return $list;
}


//日志处理


function logc($text="",$status=""){
	$list['admin_name']=session('admin_name');
	$list['u_id']=session('admin_id');
	$list['ip']=session('ip');
	$list['add_time']=now_time();
	$list['text']=$text;
	$list['status']=$status;
	return Db::name('admin_log')->insert($list);
	
	}


/**
 * 格式化字节大小
 * @param  number $size      字节数
 * @param  string $delimiter 数字和单位分隔符
 * @return string            格式化后的带单位的大小
 * @author rainfer <81818832@qq.com>
 */
function format_bytes($size, $delimiter = '') {
    $units = array(' B', ' KB', ' MB', ' GB', ' TB', ' PB');
    for ($i = 0; $size >= 1024 && $i < 5; $i++) $size /= 1024;
    return round($size, 2) . $delimiter . $units[$i];
}



/**
 * 获得配置
 */
function get_config($name){
	$site_config = db('admin_system')->field('value')->where('name', $name)->find();
    $site_config = unserialize($site_config['value']);
	return $site_config;
}


/**
 * 短信发送
 * $mobile 手机号
 * $tempalte 短信模板ID
 * $params 参数
 */
function send_sms($mobile, $template_id, $params, $sign_name,$content=null){
	// 获取短信配置
	$sms_config = get_config('sms_config');
	include_once ('./vendor/alidayu/TopSdk.php');
    date_default_timezone_set('Asia/Shanghai');
	$c = new TopClient;
	$c -> appkey = $sms_config['app_key'];
	$c -> secretKey = $sms_config['app_secret'];
	$req = new AlibabaAliqinFcSmsNumSendRequest;
	$req -> setSmsType("normal");
	if($sign_name){
		$req -> setSmsFreeSignName($sign_name);
	}else{
		$req->setSmsFreeSignName("智慧三农");
	}
	if($params){
		$req -> setSmsParam($params);
	}
	$req -> setRecNum($mobile);
	if($content){
		$req->setSmsParam('{"name":"'.$content.'"}');
	}
	$req -> setSmsTemplateCode($template_id);
	$resp = $c -> execute($req);
	return $resp;
}